<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" size="mini" :active-value="1" :incative-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirm(row)">确定</el-button>
              <el-button size="mini" type="button" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnRowEdit(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height: 60px;" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

      <!-- 放置弹层组件  -->
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @click="close">
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item label="启用">
            <!-- 如果不需要校验 就不需要写prop属性 -->
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>

          <el-form-item prop="description" label="角色描述">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="submit">确定</el-button>

                <el-button size="mini" @click="close">取消</el-button>

              </el-col>

            </el-row>

          </el-form-item>

        </el-form>

      </el-dialog>
      <!-- 放置权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          ref="permTree"
          node-key="id"
          :data="permissionData"
          :props="{label: 'name'}"
          show-checkbox
          default-expand-all
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

          </el-col>

        </el-row>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { addRole, assignPerm, delRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import { translateListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      list: [],
      showDialog: false,
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页有多少条
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未启用 关闭0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 确定删除
    async confirmDel(id) {
      await delRole(id) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 确定编辑
    async confirm(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ id: row.id, ...row.editRow })
        this.$message.success('更新角色成功')
        // eslint 误判
        // 方式一：手动消除误判提示
        // eslint-disable-next-line require-atomic-updates
        // row.isEdit = false
        Object.assign(row, {
          isEdit: false,
          ...row.editRow
        })
      }
    },
    btnRowEdit(row) {
      console.log(row)
      // vue中 动态添加属性，不及备响应式的（响应性特性 -> 数据发生变化了，视图会自动更新）
      row.isEdit = true
      // 更新缓存数据 目的：输入框/文本域的值和默认内容保持一致
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows // 赋值数据
      this.pageParams.total = total
      // 遍历数据 -> 给每一行数据中添加编辑字段isEdit -> 目的：控制行显示的内容
      this.list.forEach(item => {
        // 响应式对象.新属性 = xx（新属性不具备响应式）
        // item.isEdit = false
        // $set（目标对象，‘属性’，初始值）可以针对于目标对象所添加的属性 -> 响应式
        this.$set(item, 'isEdit', false)
        // 初始化缓存数据 -> 拷贝一份数据（大胆的去更改，不用担心影响之前的数据）
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    submit() {
      this.$refs.roleForm.validate(async add => {
        if (add) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.close()
        }
      })
    },
    close() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 获取权限列表
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermissionDialog = true
      this.permissionData = translateListToTreeData(await getPermissionList(), 0)
    },
    // 分配权限 - 确认
    async  btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys() // 获取树形组件中勾选的项
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped lang="scss">
.role-operate {
  padding: 10px;
}
</style>
